<!--广告表管理-->
<template>
  <div id="contentAdvertisement" class="app-container flex-row">
    <!-- 左侧树 -->
    <div class="conmmon-container-left scroll__y__content scrollbar-no-width" style="width:290px">
      <slotTree @currentSelected="currentSelected" />
    </div>
    <div class="conmmon-container-main flex-main">
      <div v-if="currentAdvertSlot.code" class="filter-container">
        <el-form :model="currentAdvertSlot" :inline="true">
          <el-form-item label="编码：" class="color-primary">{{ currentAdvertSlot.code }}</el-form-item>
          <el-form-item label="名称：" class="color-primary">{{ currentAdvertSlot.name }}</el-form-item>
          <el-form-item label="尺寸：" class="color-primary">{{ currentAdvertSlot.width }}px * {{ currentAdvertSlot.height }}px</el-form-item>
          <el-form-item label="描述：" class="color-primary">{{ currentAdvertSlot.description }}</el-form-item>
        </el-form>
      </div>

      <!--列表-->
      <div class="table-container flex-main">
        <div class="table-container-header">
          <table-toolbar @create="handleCreate" @refresh="handleFilter" @remove="removeRecord" />
        </div>
        <el-table
          ref="multipleTable"
          :data="list"
          header-cell-class-name="table-header"
          fit
          height="100%"
          highlight-current-row
          @selection-change="handleSelectionChange"
          @row-click="handleRowClick"
          @sort-change="sortChange">
          <el-table-column type="selection" width="60" />
          <el-table-column align="center" prop="id" label="#" width="60">
            <template slot-scope="scope">{{ scope.$index+1 }}</template>
          </el-table-column>

          <el-table-column :show-overflow-tooltip="true" label="广告图片" prop="imageUrl" min-width="400">
            <template slot-scope="scope">
              <img :src="common.getFileView(scope.row.imageUrl)" style="height: 60px;" :style="{width:(60 * currentAdvertSlot.width / currentAdvertSlot.height)+'px'}">
            </template>
          </el-table-column>
          <el-table-column label="投放周期" prop="beginDate" width="320" sortable align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="!scope.row.beginDate && !scope.row.endDate">永久</span>
              <span v-else> {{ scope.row.beginDate | formatDate('yyyy-MM-dd hh:mm:ss') }} ~ <template v-if="scope.row.endDate">{{ scope.row.endDate | formatDate('yyyy-MM-dd hh:mm:ss') }}</template><template v-if="!scope.row.endDate">永久</template></span>
            </template>
          </el-table-column>
          <el-table-column label="排序" prop="seq" width="100" align="center" sortable show-overflow-tooltip />
          <el-table-column label="操作" align="center" fixed="right" width="90">
            <template slot-scope="scope">
              <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdate(scope.row)" />
              <button-option icon="el-icon-delete" skin="danger" title="删除" @click="handleRemoveSingle(scope.row)" />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination_handler">
        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
      </div>
    </div>

    <!--新增/编辑侧边栏-->
    <side-box :show="sideBox.recordShow" :title="sideBox.title" @close="sideBox.recordShow = !sideBox.recordShow">
      <template slot="body">
        <el-form
          ref="dataForm"
          :rules="contentAdvertRules"
          :model="contentAdvertRecord"
          label-position="right"
          label-width="120px">
          <el-form-item label="图片:" prop="imageUrl">
            <single-image-upload
              v-model="contentAdvertRecord.imageUrl"
              :desc="'图片比例要求：'+currentAdvertSlot.width+'px * '+currentAdvertSlot.height+'px'"
              :catalog="constants.FILE_CATALOG_ADVERT"
              :crop-ratio="currentAdvertSlot.width / currentAdvertSlot.height" />
          </el-form-item>
          <el-form-item label="排序:" prop="seq">
            <el-input-number v-model="contentAdvertRecord.seq" placeholder="请输入" show-word-limit :min="0" :max="99999" style="width:100%" />
          </el-form-item>
          <el-form-item label="开始时间:" prop="beginDate">
            <el-date-picker
              v-model="contentAdvertRecord.beginDate"
              type="datetime"
              value-format="timestamp"
              style="width: 100%;"
              placeholder="选择日期时间" />
          </el-form-item>
          <el-form-item label="结束时间:" prop="endDate">
            <el-date-picker
              v-model="contentAdvertRecord.endDate"
              type="datetime"
              value-format="timestamp"
              style="width: 100%;"
              placeholder="选择日期时间" />
          </el-form-item>
          <el-form-item label="链接地址:" prop="linkUrl">
            <el-input v-model="contentAdvertRecord.linkUrl" maxlength="200" show-word-limit placeholder="请输入" clearable />
          </el-form-item>
          <el-form-item label="文字内容:" prop="text">
            <el-input
              v-model="contentAdvertRecord.text"
              :rows="4"
              type="textarea"
              maxlength="255"
              show-word-limit
              placeholder="请输入文字内容(限255字以内)" />
          </el-form-item>

        </el-form>
      </template>
      <template slot="foot">
        <el-button type="primary" plain @click="sideBox.status==='create'?createData():updateData()">保存 </el-button>
      </template>
    </side-box>
  </div>
</template>

<script>
import slotTree from './slotTree'
export default {
  components: { slotTree },

  data() {
    var checkEndTime = (rule, value, callback) => {
      if (value) {
        if (!this.contentAdvertRecord.beginDate) {
          return callback(new Error('请先输入开始时间'))
        }
        if (this.contentAdvertRecord.beginDate > this.contentAdvertRecord.endDate) {
          return callback(new Error('结束时间不能小于开始时间'))
        }
      }

      return callback()
    }
    return {
      currentAdvertSlot: {},
      list: [],
      total: 0,
      listQuery: {
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        keyword: undefined,
        sort: '+seq'
      },

      multipleSelectionRecords: [],
      // 固定写法
      sideBox: {
        recordShow: false,
        title: '',
        status: 'create'
      },
      contentAdvertRecord: {},
      contentAdvertRules: {
        imageUrl: [
          { required: true, message: '请输入图片', trigger: 'blur' }
        ],
        endDate: [
          { validator: checkEndTime, trigger: 'blur' }

        ]
      }
    }
  },
  created() {
  },
  methods: {
    async currentSelected(data) {
      this.currentAdvertSlot = data
      this.listQuery = {
        ...this.listQuery,
        slotId: data.id
      }
      this.handleReset()
    },
    // 表格自带方法开始
    /* 全选/反选*/
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    /* 表格行数据单击*/
    handleRowClick(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    /* 表格列排序*/
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = '+seq'
      }
      this.handleFilter()
    },
    // 表格自带方法结束

    /* 搜索*/
    handleFilter() {
      this.listQuery = {
        ...this.listQuery,
        page: 1
      }
      this.fetchData()
    },
    /* 重置*/
    handleReset() {
      this.listQuery = {
        ...this.listQuery,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        keyword: undefined,
        sort: '+seq'
      }
      this.$refs.multipleTable.clearFilter()
      this.$refs.multipleTable.clearSort()
      this.fetchData()
    },
    async fetchData() {
      const response = await this.$store.dispatch('contentAdvertPage', this.listQuery)
      this.list = response.records
      this.total = response.total
    },
    /* 新增*/
    handleCreate() {
      this.contentAdvertRecord = {
        seq: 1,
        slotId: this.listQuery.slotId
      }
      this.sideBox = {
        status: 'create',
        recordShow: true,
        title: '新增广告表'
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$store.dispatch('contentAdvertSave', this.contentAdvertRecord).then(response => {
            this.sideBox.recordShow = false
            this.$modal.msgSuccess('创建成功')
            this.handleReset()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },
    /* 编辑*/
    handleUpdate(row) {
      this.contentAdvertRecord = Object.assign({}, row) // copy obj
      this.sideBox = {
        status: 'update',
        recordShow: true,
        title: '编辑广告表'
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.contentAdvertRecord)
          this.$store.dispatch('contentAdvertUpdate', tempData).then(response => {
            this.sideBox.recordShow = false
            this.$modal.msgSuccess('修改成功')
            this.handleFilter()
          }).catch(() => {
            this.sideBox.recordShow = true
          })
        }
      })
    },

    /* 删除*/
    handleRemoveSingle(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      this.$refs.multipleTable.clearSelection()
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.removeRecord()
    },
    removeRecord() {
      if (this.multipleSelectionRecords.length > 0) {
        const ids = []
        this.multipleSelectionRecords.forEach(function(v, i) {
          ids.push(v.id)
        })
        this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('contentAdvertRemove', ids).then(response => {
            this.handleReset()
            this.$modal.msgSuccess('删除成功')
          }).catch(() => {})
        }).catch(() => { })
      } else {
        this.msgWarning('请选择要删除的记录')
      }
    }

  }
}
</script>
<style lang="scss" scoped>
</style>
